from rest_framework import serializers
from django.contrib.auth import authenticate
from .models import User, UserAddress


class UserSerializer(serializers.ModelSerializer):
    """用户序列化器"""
    
    class Meta:
        model = User
        fields = [
            'id', 'username', 'phone', 'avatar', 'nickname', 'gender',
            'birthday', 'city', 'is_vip', 'vip_expire_time', 'created_at'
        ]
        read_only_fields = ['id', 'created_at']


class UserProfileSerializer(serializers.ModelSerializer):
    """用户资料序列化器"""
    avatar = serializers.CharField(max_length=500, required=False, allow_blank=True)
    
    class Meta:
        model = User
        fields = [
            'avatar', 'nickname', 'gender', 'birthday', 'city'
        ]
    
    def validate_avatar(self, value):
        """验证头像字段，允许微信小程序的临时路径"""
        if not value:
            return value
        
        # 允许微信小程序的临时路径和正常的URL
        if (value.startswith('http://') or 
            value.startswith('https://') or 
            value.startswith('wxfile://') or
            value.startswith('blob:') or
            value.startswith('data:')):
            return value
        
        # 如果不是以上格式，也允许通过（可能是其他有效路径）
        return value


class WechatLoginSerializer(serializers.Serializer):
    """微信登录序列化器"""
    code = serializers.CharField(max_length=100, help_text="微信登录code")
    
    def validate_code(self, value):
        if not value:
            raise serializers.ValidationError("微信登录code不能为空")
        return value


class UserAddressSerializer(serializers.ModelSerializer):
    """用户地址序列化器"""
    full_address = serializers.ReadOnlyField()
    
    class Meta:
        model = UserAddress
        fields = [
            'id', 'name', 'phone', 'province', 'city', 'district',
            'detail', 'full_address', 'is_default', 'created_at'
        ]
        read_only_fields = ['id', 'created_at']
    
    def validate(self, attrs):
        # 如果设置为默认地址，需要将其他地址设为非默认
        if attrs.get('is_default', False):
            user = self.context['request'].user
            UserAddress.objects.filter(user=user, is_default=True).update(is_default=False)
        return attrs


class UserAddressCreateSerializer(serializers.ModelSerializer):
    """用户地址创建序列化器"""
    
    class Meta:
        model = UserAddress
        fields = [
            'name', 'phone', 'province', 'city', 'district',
            'detail', 'is_default'
        ]
    
    def create(self, validated_data):
        user = self.context['request'].user
        
        # 如果设置为默认地址，将其他地址设为非默认
        if validated_data.get('is_default', False):
            UserAddress.objects.filter(user=user, is_default=True).update(is_default=False)
        
        # 如果是第一个地址，自动设为默认
        if not UserAddress.objects.filter(user=user).exists():
            validated_data['is_default'] = True
        
        return UserAddress.objects.create(user=user, **validated_data)